//项目权属管理
import * as React from 'react';
import {
  Table,
  Form,
  Select,
  Input,
  Button,
  Col,
  Row,
  Modal,
  Checkbox,
  notification,
  DatePicker,
  Spin,
  message,
  Upload,
  Icon
} from 'antd';
import axios from 'axios';
import Api from '../../services/apis';
import moment from 'moment';

import Link from 'umi/link';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './style.less';

const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const RangePicker = DatePicker.RangePicker;
const Dragger = Upload.Dragger;
@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class EnergyCostMaintenance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      sTransferUnit: [],//划转单位下拉
      sCommunitiesByTrUnit: [],//小区信息
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
      "transfer_unit": "",//划转单位名称
      "community_name": "",//小区名称
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
      "fee_type": "",//费用类型
      "begin_time": "",//开始时间
      "end_time": "",//终止时间
      "currentPage": 1,//当前页
      "pageSize": 10,//页大小
      feeType: [],
      tableData: [],
      fileIds: [],
      loading: false,
      current: 1,
      totalSize: 0,
      m_current: 1,
      m_pageSize: 5,
      submitFlag: '',
      rooms: [],
      cabinets: [],
      boxs: [],
      upload: false,
      modalLoading: false,
      bags: [],
      keyId: '',
      searchData: {
        address: '',
        projectCode: '',
        projectName: '',
        constructionType: '',
        begin_time: '',
        end_time: '',
        fee_type: '',
        currentPage: 1,
      },
      modalTitle: '',
      feeDate: '',
      statisticDate: '',
      statisticType: [],
      nowItem: '',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      buildingType: ['新建工程', '扩建工程', '翻建工程', '改建工程', '续建工程'],
      currentSteps: ['审批阶段', '前期', '中期', '后期', '工程验收', '结算审计', '已结项']
    };
  }

  handlePreviewCancel() {
    this.setState({ previewVisible: false })
  }

  handlePreview(file) {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  removePic(info) {
    let p = new Promise((resp, rej) => {
      axios.get(Api.deleteFile, {
        params: {
          fileId: info.response
        }
      }).then((res) => {
        if (Number(res.data.code) === 1 || Number(info.response) === 0) {
          message.success(res.data.msg);
          resp('success');
        } else {
          message.error(res.data.msg);
          rej('error');
        };
      });
    });
    return p;
  }

  handleChange(info) {
    const { fileList } = info;
    this.setState({ fileList });
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 图片上传成功！`);

      let fileIds = this.state.fileIds;
      fileIds.push(info.file.response);

      this.setState({ fileIds });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 图片上传失败！`);
    }
  }



  changeDate(type, dates, dateStrings) {
    switch (type) {
      case 'search':
        this.setState({
          "begin_time": dateStrings[0],//开始时间
          "end_time": dateStrings[1],//终止时间
        });
        break;
      case 'feeDate':
        this.setState({
          feeDate: dateStrings
        });
        break;
      case 'statisticDate':
        this.setState({
          statisticDate: dateStrings
        });
        break;

      default:
        this.setState({
          "begin_time": dateStrings[0],//开始时间
          "end_time": dateStrings[1],//终止时间
        });
        break;
    }
  }

  componentWillMount() {
    this.getAllTransferUnit();
    this.getAllFeeType();
    this.getAllStatisticType();
    this.getTableData(this.state.searchData);
  }

  modalSubmit() {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let param = {};
        for (let key in values) {
          param[key.slice(2)] = values[key];
        };
        param.completionTime = moment(param.completionTime).format('YYYY-MM-DD');
        param.startTime = moment(param.startTime).format('YYYY-MM-DD');
        param.fileIds = this.state.fileIds;

        this.maintainData(param);
      }
    })
  }
  setModalVisible(modalVisible, modalType, nowItem) {
    //this.resetForm();
    let modalTitle = '';
    switch (modalType) {
      case 'new':
        modalTitle = '新建';
        break;
      default:
        modalTitle = '编辑';
        break;
    };
    if (!modalVisible) {
      this.setState({ fileIds: [] });
    };
    if (modalType === 'updata') {
      axios.get(Api.detailProject, {
        params: { projectCode: nowItem.projectCode }
      }).then(res => {
        let fileList = [];
        let fileIds = res.data.fileId.split(',');
        for (let i = 0, len = res.data.fileList.length; i < len; i++) {
          fileList.push(
            {
              uid: i,
              name: res.data.fileList[i].uploadName,
              status: 'done',
              url: `http://192.168.50.55:55555/res_file/${res.data.fileList[i].filePath}`
            }
          );
        }
        this.setState({
          fileList,
          fileIds
        });
      });
    }

    this.setState({ modalVisible, modalType, modalTitle, nowItem });
  }

  resetForm() {
    this.props.form.resetFields();
    const searchData = {
      transfer_unit: '',
      community_name: '',
      building_code: '',
      house_code: '',
      begin_time: '',
      end_time: '',
      fee_type: '',
      currentPage: 1,
      pageSize: 10,
    };
    this.setState({ searchData });
    this.getTableData(searchData);
  }

  query = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      values.currentPage = this.state.searchData.currentPage;
      this.setState({
        searchData: values
      });
      this.getTableData(values);
    });
  }

  getTableData(data) {
    this.setState({
      loading: true
    });
    axios.post(Api.searchList, data).then((res) => {
      let tableData = res.data.list;
      for (let i = 0, len = tableData.length; i < len; i++) {
        tableData[i].key = i;
      };
      this.setState({
        tableData,
        loading: false,
        totalSize: res.data.totalSize
      });
    });
  }

  pageChange = (page) => {
    this.setState({ current: page }, () => {
      let data = this.state.searchData;
      data.currentPage = page;
      this.getTableData(data);
    })
  }


  getAllTransferUnit() {
    axios.get(Api.getAllTransferUnit).then((res) => {
      this.setState({
        sTransferUnit: res.data.data
      });
    });
  }

  changeTransferUnit(index, val) {
    this.getCommunitiesByTrUnit(val.props.children);
    this.setState({
      sCommunitiesByTrUnit: [],//小区信息
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "community_name": "",//小区名称
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_community_name": "",//小区名称
        "m_building_code": "",//楼栋代号
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }
  maintainData(data) {
    this.setState({
      modalLoading: true
    });
    const type = this.state.modalType;
    const nowItem = this.state.nowItem;
    data.fileId = data.fileIds.join();
    switch (type) {
      case 'new':
        axios.post(Api.addProject, data).then((res) => {
          if (Number(res.data.code) !== 1) {
            message.error(`新建失败，${res.data.msg}`);
          } else {
            message.success(res.data.msg);
            this.setModalVisible(false);
            this.getTableData(this.state.searchData);
          };
          this.setState({
            modalLoading: false
          });
        });
        break;

      case 'updata':
        axios.post(Api.updateProject, { ...nowItem, ...data }).then((res) => {
          if (Number(res.data.code) !== 1) {
            message.error(`新建失败，${res.data.msg}`);
          } else {
            message.success(res.data.msg);
            this.setModalVisible(false);
            this.getTableData(this.state.searchData);
          };
          this.setState({
            modalLoading: false
          });
        });
        break;
    }

  }
  changeCommunitiesByTrUnit(index) {
    this.getBuildsByProjCode(this.state.sCommunitiesByTrUnit[index].projectCode);
    this.setState({
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_building_code": "",//楼栋代号
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }
  changeBuildsByProjCode(index) {
    this.getAllHousesByBuildingCode(this.state.sBuildsByProjCode[index].buildingCode);
    this.setState({
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }

  getCommunitiesByTrUnit(transfer_unit) {
    axios.post(Api.getCommunitiesByTrUnit, { transfer_unit }).then((res) => {
      this.setState({
        sCommunitiesByTrUnit: res.data.data
      });
    });
  }

  getBuildsByProjCode(project_code) {
    axios.post(Api.getBuildsByProjCode, { project_code }).then((res) => {
      this.setState({
        sBuildsByProjCode: res.data.data
      });
    });
  }
  getAllHousesByBuildingCode(building_code) {
    axios.post(Api.getAllHousesByBuildingCode, { building_code }).then((res) => {
      this.setState({
        sHousesByBuildingCode: res.data.data
      });
    });
  }

  getAllFeeType() {
    axios.get(Api.getAllFeeType).then((res) => {
      this.setState({
        feeType: res.data.data
      });
    });
  }

  getAllStatisticType() {
    axios.get(Api.getAllStatisticType).then((res) => {
      this.setState({
        statisticType: res.data.data
      });
    });
  }
  deleteFeeMaintain(item) {
    Modal.warning({
      title: '确认删除本条数据？',
      content: [<p>注意，删除后不可恢复。</p>, <p>esc关闭此窗口。</p>],
      okText: '确认删除',
      onOk: () => {
        axios.get(Api.deleteProject, {
          params: {
            projectCode: item.projectCode
          }
        }).then((res) => {
          if (Number(res.data.code) === 0) {
            message.error(`删除失败${res.data.msg}`);
          } else {
            message.success(res.data.msg);
            this.getTableData(this.state.searchData);
          };
        });
      }
    });
  }
  render() {
    const that = this;
    const { getFieldDecorator } = this.props.form;
    const {
      currentUserLoading,
    } = this.props;

    const columns = [
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName'
      },
      {
        title: '项目编号',
        dataIndex: 'projectCode',
        key: 'projectCode'
      },
      {
        title: '划转单位',
        dataIndex: 'transferUnit',
        key: 'transferUnit',
      },
      {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
      },
      {
        title: '竣工时间',
        dataIndex: 'completionTime',
        key: 'completionTime',
      },
      {
        title: '工程预算',
        dataIndex: 'constructionBudget',
        key: 'constructionBudget',
      },
      {
        title: '工程结算',
        dataIndex: 'constructionSettlement',
        key: 'constructionSettlement',
      },
      {
        title: '建设性质',
        dataIndex: 'constructionTypeStr',
        key: 'constructionTypeStr',
      },
      {
        title: '当前阶段',
        dataIndex: 'currentStepStr',
        key: 'currentStepStr',
      },
      {
        title: '投资额度',
        dataIndex: 'investmentAmount',
        key: 'investmentAmount',
      },
      {
        title: '开工时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '创建人',
        dataIndex: 'createUser',
        key: 'createUser',
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        render: (item, record) => (
          <span>
            <Link target='_blank' to={{
              pathname: '/fe/dataMaintenance/projectDetails',
              search: `?projectCode=${item.projectCode}`
            }}>
              <Button type='primary'>详情</Button>
            </Link>
            &emsp;
              <Button type='primary' onClick={this.setModalVisible.bind(this, true, 'updata', item)}>编辑</Button>
            &emsp;
            <Button type='primary' onClick={this.deleteFeeMaintain.bind(this, item)}>删除</Button>
          </span>
        ),
      },
    ];
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div>点击上传图片</div>
      </div>
    );
    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>工程项目管理</p>
              <p>PROJECT MANAGEMENT</p>
            </div>
          </div>
          <div className="pom">
            <div className='mrb15'>
              <Form layout='inline' align='left' onSubmit={this.query.bind(this)}>
                <FormItem label='项目编号：'>
                  {getFieldDecorator('projectCode')(<Input placeholder="请输入项目编号" />)}
                </FormItem>
                <FormItem label='项目名称：'>
                  {getFieldDecorator('projectName')(<Input placeholder="请输入项目名称" />)}
                </FormItem>
                <FormItem label='建设性质：'>
                  {
                    getFieldDecorator('constructionType')(
                      <Select
                        placeholder="请选择建设性质"
                      >
                        <Option value={1} key={1}>新建工程</Option>
                        <Option value={2} key={2}>扩建工程</Option>
                        <Option value={3} key={3}>翻建工程</Option>
                        <Option value={4} key={4}>改建工程</Option>
                        <Option value={5} key={5}>续建工程</Option>
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem label='坐落：'>
                  {getFieldDecorator('address')(<Input placeholder="请输入坐落" />)}
                </FormItem>
                <Row gutter={24} style={{ textAlign: 'center' }}>
                  <Button icon='search' type='primary' htmlType='submit'>搜索</Button>
                  &emsp;
                  <Button icon="plus-circle" type="primary" htmlType='button' onClick={this.setModalVisible.bind(this, true, 'new')}>新建</Button>
                  &emsp;
                  <Button icon="reload" type="primary" htmlType='button' onClick={this.resetForm.bind(this)}>重置</Button>
                </Row>
              </Form>
            </div>
            <Spin spinning={this.state.loading}>
              <Table
                bordered={true}
                scroll={{ x: true }}
                columns={columns}
                dataSource={that.state.tableData}
                pagination={{
                  current: that.state.current,
                  onChange: this.pageChange.bind(this),
                  total: that.state.totalSize,
                  showTotal: total => `共 ${total} 项`
                }} />
            </Spin>
          </div>
          <Modal
            title={this.state.modalTitle}
            destroyOnClose={true}
            centered
            visible={this.state.modalVisible}
            width={830}
            className='modalAlign'
            onCancel={this.setModalVisible.bind(this, false)}
            footer={[
              <Button key="back" onClick={this.setModalVisible.bind(this, false)}>取消</Button>,
              <Button disabled={this.state.upload} key="submit" type="primary" loading={this.state.modalLoading} onClick={this.modalSubmit.bind(this)}>
                提交
              </Button>,
            ]}
          >
            <Form layout='inline' align='left' onSubmit={this.query.bind(this)}>
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="划转单位：">
                    {
                      getFieldDecorator('m_transferUnit', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.transferUnit : '',
                        rules: [{ required: true, message: '请输入划转单位!' }],
                      })(
                        <Input placeholder='请输入划转单位' />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="地址：">
                    {
                      getFieldDecorator('m_address', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.address : '',
                        rules: [{ required: true, message: '请输入地址!' }],
                      })(
                        <Input placeholder='请输入地址' />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="项目编号：">
                    {
                      getFieldDecorator('m_projectCode', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.projectCode : '',
                        rules: [{ required: true, message: '请输入项目编号!' }],
                      })(
                        <Input placeholder='请输入项目编号' disabled={this.state.modalType === 'updata' ? true : false} />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="项目名称：">
                    {
                      getFieldDecorator('m_projectName', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.projectName : '',
                        rules: [{ required: true, message: '请输入项目名称!' }],
                      })(
                        <Input placeholder='请输入项目名称' />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='建设性质：'>
                    {
                      getFieldDecorator('m_constructionType', {
                        initialValue: this.state.modalType === 'updata' ? this.state.buildingType[this.state.nowItem.constructionType - 1] : '',
                      })(
                        <Select
                          placeholder="请选择建设性质"
                        >
                          <Option value={1} key={1}>新建工程</Option>
                          <Option value={2} key={2}>扩建工程</Option>
                          <Option value={3} key={3}>翻建工程</Option>
                          <Option value={4} key={4}>改建工程</Option>
                          <Option value={5} key={5}>续建工程</Option>
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='投资额度：'>
                    {getFieldDecorator('m_investmentAmount', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.investmentAmount : '',
                      rules: [{ required: true, message: '请输入投资额度!' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }],
                    })(<Input placeholder="请输入投资额度" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='工程预算：'>
                    {getFieldDecorator('m_constructionBudget', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.constructionBudget : '',
                      rules: [{ required: true, message: '请输入工程预算!' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }],
                    })(<Input placeholder="请输入工程预算" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='工程结算：'>
                    {getFieldDecorator('m_constructionSettlement', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.constructionSettlement : '',
                      rules: [{ required: true, message: '请输入工程结算!' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }],
                    })(<Input placeholder="请输入工程结算" />)}
                  </FormItem>
                </Col>
                <Col
                  span={8}

                >
                  <FormItem
                    label='开工时间：'
                  >{getFieldDecorator('m_startTime', {
                    initialValue: this.state.modalType === 'updata' ? moment(this.state.nowItem.startTime) : '',
                    rules: [{ required: true, message: '请输入开工时间!' }],
                  })(
                    <DatePicker
                      ranges={{ '今天': [moment(), moment()], '本月': [moment().startOf('month'), moment().endOf('month')] }}
                      onChange={this.changeDate.bind(this, 'startTime')}
                    />)}
                  </FormItem>
                </Col>
                <Col
                  span={8}

                >
                  <FormItem
                    label='竣工时间：'
                  >{getFieldDecorator('m_completionTime', {
                    initialValue: this.state.modalType === 'updata' ? moment(this.state.nowItem.completionTime) : '',
                    rules: [{ required: true, message: '请输入竣工时间!' }],
                  })(
                    <DatePicker
                      ranges={{ '今天': [moment(), moment()], '本月': [moment().startOf('month'), moment().endOf('month')] }}
                      onChange={this.changeDate.bind(this, 'completionTime')}
                    />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label='当前阶段：'>
                    {
                      getFieldDecorator('m_currentStep', {
                        initialValue: this.state.modalType === 'updata' ? this.state.currentSteps[this.state.nowItem.currentStep - 1] : '',
                      })(
                        <Select
                          placeholder="请选择当前阶段"
                        >
                          <Option value={1} key={1}>审批阶段</Option>
                          <Option value={2} key={2}>前期</Option>
                          <Option value={3} key={3}>中期</Option>
                          <Option value={4} key={4}>后期</Option>
                          <Option value={5} key={5}>工程验收</Option>
                          <Option value={6} key={6}>结算审计</Option>
                          <Option value={7} key={7}>已结项</Option>
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={24}>
                  <Upload
                    action={Api.projectManagementUploadFile}
                    listType="picture-card"
                    accept='.jpg,.jpeg,.png,.gif'
                    fileList={this.state.fileList}
                    onPreview={this.handlePreview.bind(this)}
                    onChange={this.handleChange.bind(this)}
                    onRemove={this.removePic.bind(this)}
                  >
                    {uploadButton}
                  </Upload>
                  <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handlePreviewCancel.bind(this)}>
                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                  </Modal>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const WrappedApp = Form.create()(EnergyCostMaintenance);

export default WrappedApp;
